import json
import pathlib
import _thread
import time

import win32con
import win32gui
from win32gui import *


class Config:
    def __init__(self, config_path=None):
        self.config_path = config_path
        self.resolving_power = None
        self.app_name = None
        self.init = True
        self.thread = False
        self.message_set = set()
        self.run_order = []
        self.app = False

    def read_config(self):
        """读取配置文件"""
        with open(self.config_path, "r") as file:
            _json = file.read()
        self.set(_json)
        if self.check() and not self.thread:
            self.thread = True
            self.set_thread()
        return self.to_string()

    def set_thread(self):
        """开启一个子进程监视选择应用程序是否被打开，如果打开，调整分辨率"""
        _thread.start_new_thread(self.adjust_conf_for_window, ())

    def adjust_conf_for_window(self):
        """调整窗口至配置所需"""
        self.message_set = set()
        while 1:
            while 1:
                if self.app_name not in self.get_apps():
                    time.sleep(1)
                    continue
                self.message_set.add(f"检测到{self.app_name}已打开，已根据配置调整")
                self.move_app()
                self.app = True
                break
            while 1:
                if self.app_name in self.get_apps():
                    time.sleep(5)
                    continue
                self.app = False
                self.message_set.add(f"检测到{self.app_name}已关闭")
                break

    def check(self):
        """检查配置文件"""
        _dict = self.__dict__.copy()
        for i in _dict:
            if self.__dict__[i] is None:
                self.init = False
                return False
        if len(self.resolving_power.split("x")) != 2:
            self.init = False
            return False
        return True

    def save(self):
        """保存配置文件"""
        _dict = self.__dict__
        _dict["config_path"] = str(self.config_path)
        _dict["message_set"] = ""
        with open(self.config_path, "w", encoding="utf-8") as file:
            _dict = json.dumps(_dict)
            file.write(_dict)

    def set(self, json_dict):
        try:
            _dict = json.loads(json_dict)
        except json.decoder.JSONDecodeError:
            return False
        try:
            self.config_path = pathlib.Path(self.config_path)
            self.resolving_power = _dict["resolving_power"]
            self.app_name = _dict["app_name"]
            self.run_order = _dict["run_order"]
            self.app = False
            self.thread = False
            self.message_set = set()
        except KeyError:
            return False
        return True

    def to_string(self):
        _dict = self.__dict__
        _dict["message_set"] = ""
        _dict["config_path"] = str(self.config_path)
        result = json.dumps(_dict, indent=2, ensure_ascii=False)
        return result

    def move_app(self, is_top=False):
        """根据分辨率移动并调整窗口"""
        hwnd = win32gui.FindWindow(None, self.app_name)
        win32gui.SetWindowPos(hwnd, win32con.HWND_NOTOPMOST, 0, 0, int(self.resolving_power.split("x")[0]),
                              int(self.resolving_power.split("x")[1]), win32con.SWP_SHOWWINDOW)
        if is_top:
            win32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST, 0, 0, int(self.resolving_power.split("x")[0]),
                                  int(self.resolving_power.split("x")[1]), win32con.SWP_SHOWWINDOW)

    @staticmethod
    def get_apps():
        """获取应用程序进程列表"""
        list_lpWindowName = []
        titles = set()

        def foo(hwnd, nouse):
            # 去掉下面这句就所有都输出了，但是我不需要那么多
            if IsWindow(hwnd) and IsWindowEnabled(hwnd) and IsWindowVisible(hwnd):
                titles.add(GetWindowText(hwnd))

        EnumWindows(foo, 0)
        lt = [t for t in titles if t]
        lt.sort()
        for t in lt:
            list_lpWindowName.append(t)
        return list_lpWindowName